<template>
	<div id="order">
	     <!-- 导航栏 -->
	     <van-nav-bar
			  title="填写订单"
			  left-arrow
			  :fixed=true
              :border=true
			  @click-left="onClickLeft"
			></van-nav-bar>


          

     <van-cell-group v-if="time" style="margin-top: 3rem">
			   <van-cell title="请选择鲜活蔬菜送达时间"   @click="showStartTime()" v-model="startTime"  is-link/>
			    <van-popup 
		     		v-model="showStart" 
			    	position="bottom" 
			        :style="{ height: '40%' }">
		        <van-datetime-picker 
			        v-model="startTime" 
			        type="time" 
			        :min-hour="minhours"
				    @confirm="confirmStartFn()" 
		        @cancel="cancelFn()" />
		       </van-popup>
			   <van-cell title="订单详情" value="内容" is-link/>
			</van-cell-group> 
		     <van-cell-group v-else style="margin-top: 3rem">
			   <van-cell title="订单详情" value="内容" is-link/>
			</van-cell-group>


			<van-cell-group  style="margin-top: 0.6rem">
			   <van-cell title="支付方式" value="微信" is-link/>
			</van-cell-group>

			<van-cell-group  style="margin-top: 0.6rem">
			   <van-cell title="备注">
                  <input type="text" v-model="beizhu" placeholder="选填，备注您的特殊需求!">
			   </van-cell>
			</van-cell-group>


			<van-cell-group v-if="this.userInfo.vip===1&&this.userInfo.jifen" style="margin-top: 0.6rem">
			   <van-cell title="商品金额" >{{totalPrice|moneyFormat}}</van-cell>
              <van-cell title="会员价">{{memberPrice|moneyFormat}}</van-cell>
			   <van-cell title="积分抵扣">-{{discount|moneyFormat}}</van-cell>
			</van-cell-group>
			<van-cell-group v-else-if="this.userInfo.vip===1&&!this.userInfo.jifen" style="margin-top: 0.6rem">
			   <van-cell title="商品金额" >{{totalPrice|moneyFormat}}</van-cell>
			   <van-cell title="会员价">{{memberPrice|moneyFormat}}</van-cell>
			</van-cell-group>
          	<van-cell-group v-else-if="this.userInfo.vip===0&&this.userInfo.jifen" style="margin-top: 0.6rem">
			   <van-cell title="商品金额" >{{totalPrice|moneyFormat}}</van-cell>
			    <van-cell title="积分抵扣">-{{discount|moneyFormat}}</van-cell>
			</van-cell-group>
	    	<van-cell-group v-else-if="this.userInfo.vip===0&&!this.userInfo.jifen" style="margin-top: 0.6rem">
			   <van-cell title="商品金额" >{{totalPrice|moneyFormat}}</van-cell>
			</van-cell-group>


			<van-notice-bar wrapable :scrollable="false">
			   *一般蔬菜商品每天15点前下单，16点前送达，超过15点下的订单将于第二天16点前送达；鲜活类蔬菜商品于当天在您选择的送达时间内送达，最快1小时后送达。
			</van-notice-bar>
            
            <div class="submit">
               <div style="float:right">
                 <span style="color:#323233;font-size:1.0rem">实付:</span>
                 <span style="color:#ee0a24;font-size: 1.3rem;margin-right:0.5rem">{{price|moneyFormat}}</span>
                 <span><van-button type="danger" @click="queren">提交订单</van-button></span>
                </div>
            </div>


	       <transition name="router-slider" mode="out-in">
	          <router-view></router-view>
           </transition>
	</div>
</template>

<script>
import { Dialog } from 'vant'
import {mapState,mapMutations} from "vuex"
import { DatetimePicker, NoticeBar ,Toast} from 'vant'
 import {createyzfOrder,createwzfOrder,createdOrderDetail,createJF,updateJF} from './../../service/api/index'
	export default{
		name:"Order", 
		data(){
            return {
         	show:false, 
          beizhu:'',
			    startTime: '',// 开始时间
			    showStart: false, // 用来显示弹出层
			    time:false, //鲜活类蔬菜送达时间选择的显示
    
            }
		},

		 computed:{
              ...mapState(['shopCart','userInfo']),
             
              minhours(){
             	return  (new Date()).getHours()+1;
             },
             //总金额 
             totalPrice(){
              	return this.$route.params.totalPrice;
             },
             //会员价
             memberPrice(){
             	return (this.$route.params.totalPrice*0.8).toFixed(2);
             },
             //积分可以抵扣的金额
             discount(){
                 if (this.userInfo.vip===1) {
                     //vip用户
                      if(this.memberPrice*10>this.userInfo.jifen){
                      	  //积分不够
                           return (this.userInfo.jifen*0.1).toFixed(2); 
                      }else{
                      	  //积分够扣
                           return this.memberPrice;
                      };
                 }else{
                 	 //非vip用户
                        if (this.totalPrice*10>this.userInfo.jifen) {
                             //积分不够
                             return (this.userInfo.jifen*0.1).toFixed(2);
                        }else{
                             //积分够扣
                             return this.totalPrice;
                        };
                 }

             },
              price(){
                 // if (this.userInfo.vip===1){
                 //    return (this.memberPrice-this.discount)*100;
                 // }else{
                 // 	 return (this.totalPrice-this.discount)*100;
                 // }

                   if (this.userInfo.vip===1&&this.userInfo.jifen) {
                   	   return (this.memberPrice-this.discount).toFixed(2);
                   }else if (this.userInfo.vip===1&&!this.userInfo.jifen) {
                   	   return (this.memberPrice);
                   } else if (this.userInfo.vip===0&&this.userInfo.jifen) {
                   	   return (this.totalPrice-this.discount).toFixed(2);
                   }else if (this.userInfo.vip===0&&!this.userInfo.jifen) {
                       return this.totalPrice;
                   }
              	
              }
             
         },
		mounted(){
		// 	 判断订单中是否包含鲜活类蔬菜，有鲜活蔬菜显示选择送达时间
	         let shopCart = this.shopCart;
		     Object.values(shopCart).forEach((goods,index)=>{
                 //console.log(goods);
                  if (goods.checked===1&&goods.pzleixing===2) {
                  	 this.time = true;
                  }
		    })


		},
		methods:{
			 ...mapMutations(["DELETE_CART","UPDATE_JIFEN"]),  //拿到mutations.js  里面的REDUCE_CART方法,记得先导入
			//点击了左边
             onClickLeft(){
                this.$router.back();
             },
             //点击提交订单，弹框提示'支付成功'随后跳转到支付成功页面,
             queren(){  
                        if (this.time===true) {
                          // console.log(this.startValue)
                              if(this.startTime===''){
                                   Toast.fail("请选择鲜活蔬菜送达时间！");
                                    return false;
                              }
                        };
                      	Dialog.confirm({
              					  message: '你正在使用微信支付，是否继续支付？'
              					}).then(async () => {
                                        //成功支付,入库操作，生成已经支付的订单表，订单表状态status=1(已付款状态)，跳转到支付成功页面。
                                        //积分记录表添加该条记录(花费得到积分，抵扣积分)，
                                //    console.log(this.$route.params.totalPrice);
                              console.log(this.price);
              					      let result = await createyzfOrder(this.userInfo.token,this.beizhu,this.$route.params.totalPrice,this.startTime);
                                        console.log(result);
                                       if (result.status==='200') {
                                             //创建订单详情表，将选中商品移除购物车表
                                             // console.log(result.bianhao);
                                             let res = await createdOrderDetail(result.bianhao);
                                              console.log(res);
                                               if (res.status==='200') {
                                                //1.同步本地数据
                                                //console.log(this.shopCart);
                                                 Object.values(this.shopCart).forEach((goods,index)=>{
                                                 	      let goodsId=goods.id;
                                                         if (goods.checked===1) {
                                                              this.DELETE_CART({goodsId});
                                                         }
                                                 });


                                                 //2.创建积分记录(有积分生成两条(购买蔬菜所获积分，抵扣蔬菜所抵积分);没积分生成1条，(购买蔬菜所获积分))
                                               if (this.userInfo.vip===1&&this.userInfo.jifen) {
                                             	 //2.1有积分会员,订单记录表生成两条记录(购买蔬菜获得积分，抵扣蔬菜扣除的积分)
                                             	//  console.log(this.memberPrice-this.price);
                                             	    let jfresult = await createJF(this.userInfo.token,result.bianhao,this.totalPrice,this.memberPrice-this.price);
                                             	       console.log(jfresult);
                                             	        //积分记录生成，修改用户user表用户的积分jifen，修改本地用户积分数据
                                                        if (jfresult.status==='200') {
                                                              let res = await updateJF(this.userInfo.token,jfresult.add,jfresult.reduce);
                                                              console.log(res);
                                                              if (res.status==='200') {
                                                                   //储存本地
                                                                   let jifen = res.data;
                                                                   this.UPDATE_JIFEN({jifen});
                                                              };
                                                        }  
                                               }else if (this.userInfo.vip===0&&this.userInfo.jifen) {
                                                 //2.2有积分非会员，订单记录表同样生成两条记录(购买蔬菜获得积分，抵扣蔬菜扣除的积分)
                                                   let jfresult = await createJF(this.userInfo.token,result.bianhao,this.totalPrice,this.totalPrice-this.price);
                                                   console.log(jfresult);
                                                       //积分记录生成，修改用户user表用户的积分jifen，修改本地用户积分数据
                                                        if (jfresult.status==='200') {
                                                              let res = await updateJF(this.userInfo.token,jfresult.add,jfresult.reduce);
                                                              console.log(res);
                                                              if (res.status==='200') {
                                                                   //储存本地
                                                                   let jifen = res.data;
                                                                   this.UPDATE_JIFEN({jifen});
                                                              };
                                                        }                                         
                                               }else{
                                               //2.3没积分，订单记录表生成一条记录(购买积分获得的积分)
                                                   let jfresult = await createJF(this.userInfo.token,result.bianhao,this.totalPrice,0);
                                                   console.log(jfresult);
                                                   //积分记录生成，修改用户user表用户的积分jifen，修改本地用户积分数据
                                                   if (jfresult.status==='200') {
                                                          let res = await updateJF(this.userInfo.token,jfresult.add,0);
                                                          console.log(res);
                                                               if (res.status==='200') {
                                                                   //储存本地
                                                                   let jifen = res.data;
                                                                   this.UPDATE_JIFEN({jifen});
                                                              };

                                                   }
                                               };

                                                //跳转到支付成功页面
                                                   this.$router.push({ name: 'success',params:{bianhao:result.bianhao,price:this.price} });
                                               }             
                                       }
              					}).catch(async () => {
              						//取消支付,入库操作，生成未付款的订单表和订单详情表，订单表状态status=-1(未付款状态)，跳转到待付款订单页面
              					    // console.log("已取消支付");
              					     let resultw = await createwzfOrder(this.userInfo.token,this.beizhu,this.$route.params.totalPrice,this.startTime);
                                       console.log(resultw);                        
                                        if (resultw.status==='200') {
                                            //创建订单详情表，将选中商品移除购物车表
                                            // console.log(result.bianhao);
                                           let res = await createdOrderDetail(resultw.bianhao);
                                           console.log(res);
              	                           if(res.status==='200'){
              	                               //同步本地数据
              	                                //console.log(this.shopCart);
              	                               Object.values(this.shopCart).forEach((goods,index)=>{
              	                           	      let goodsId=goods.id;
              		                                   if (goods.checked===1) {
              		                                        this.DELETE_CART({goodsId});
              		                                    }
              	                                  });
              	                                  //跳转到未付款订单列表页面
                                                       this.$router.push({ name: 'DzfOrder'});
                                               }       
                                        }                   
                                      
              					});
                 },

            showStartTime() {
					   this.showStart = true;
			     },
			    confirmStartFn() { // 确定按钮
					    this.showStart = false;
			     },
			    cancelFn(){
					   this.showStart = false;
				},

		},

	}
</script>

<style scoped>
    #order{
    	width:100%;
    	height:100%;
    	background-color:#f5f5f5;
    }
    
    .router-slider-enter-active,.router-slider-leave-active{
    	transition:all 0.3s;
    }

    .router-slider-enter,.router-slider-leave-active{
    	transform:translate3d(2rem,0,0);
    	opacity:0;
    }

    .submit{
    	position: fixed;
	    bottom: 0;
	    left: 0;
	    z-index: 100;
	    width: 100%;
	    background-color: #fff;
    }
</style>